package com.sec.etech.process.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.process.mapper.SppRouteStepMapper;
import com.sec.etech.process.model.SppRouteStep;
import com.sec.etech.sys.util.DbUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class SppRouteStepService extends ServiceImpl<SppRouteStepMapper, SppRouteStep> {
    @Resource
    private JdbcTemplate jdbcTemplate;

    //根据设备工种获取工作中心
    public List getWorkCenterByEq(Long worktypeId){
        String sql = "select t2.workcenter_id, t2.`code`,t2.`name` from spp_step_workcenter_worktype t1,proc_process_z_work_center t2 " +
                "where t1.workcenter_id=t2.workcenter_id and t1.worktype_id=?";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql, worktypeId);
        List objectList = new ArrayList<>();
        if(list!=null && list.size()>0){
            for(Map<String,Object> map:list){
                objectList.add(map);
            }
        }
        return objectList;
    }

    //校验工序号是否重复
    public String checkStepNo(JSONObject object){
        Map<String, String> stepNoMap = new HashMap<>();//工步号
        Map<String, Integer> stepNoNumMap = new HashMap<>();//工步号以及数量
        Long routeRevId = object.getLong("route_rev_id");
        //查询数据库
        List<SppRouteStep> stepList = super.list(new LambdaQueryWrapper<SppRouteStep>().eq(SppRouteStep::getRouteRevId, routeRevId));
        if(stepList!=null && stepList.size()>0){
            for(SppRouteStep step:stepList){
                stepNoMap.put(step.getRouteStepId().toString(), step.getStepNum());
            }
        }
        //查询待保存/更新对象
        List<JSONObject> objectList = (List<JSONObject>) object.get("dataList");
        for (JSONObject obj : objectList) {
            String flag = obj.getString("flag");
            String routeStepId = obj.getString("route_step_id") != null ? obj.getString("route_step_id") : null;
            if(!"del".equals(flag)){//删除
                String opNo = obj.getString("op_no");
                String stepNo = obj.getString("step_no");
                if (StringUtil.isNotEmpty(routeStepId)) {
                    stepNoMap.put(routeStepId, this.getStepNum(opNo, stepNo));
                }
            }else {
                stepNoMap.remove(routeStepId);
            }
        }
        //检查已有ID的工步是否重复
        for(Map.Entry<String, String> entry:stepNoMap.entrySet()) {
            if(stepNoNumMap.containsKey(entry.getValue())) {
                Integer num = stepNoNumMap.get(entry.getValue());
                stepNoNumMap.put(entry.getValue(), num + 1);
            }else {
                stepNoNumMap.put(entry.getValue(), 1);
            }
        }
        //检查新增/修改工序卡中是否有工步号重复
        for (JSONObject obj : objectList) {
            if (obj.getLong("route_step_id") == null || obj.getLong("route_step_id") == 0) {
                String key = this.getStepNum(obj.getString("op_no"), obj.getString("step_no"));
                if (stepNoNumMap.containsKey(key)) {
                    Integer num = stepNoNumMap.get(key);
                    stepNoNumMap.put(key, num + 1);
                } else {
                    stepNoNumMap.put(key, 1);
                }
            }
        }
        String msg = "";
        for(Map.Entry<String, Integer> entry:stepNoNumMap.entrySet()) {
            if(entry.getValue()>1){
                msg = entry.getKey() + "、" + msg;
            }
        }
        if(!"".equals(msg)){
            return "该工步号已存在，无法修改：" + msg.substring(0, msg.length()-1);
        }
        return "success";
    }

    //获取工步排序号
    public String getStepNum(String opNo, String stepNo){
        return String.format("%03d", Integer.parseInt(opNo)) + String.format("%03d", Integer.parseInt(stepNo));
    }

    public void delStep(SppRouteStep step, String amendNum) {

        // 修改单 修改原有记录时逻辑删除
        boolean needLogicDel = false;
//        String checkAmdRouteSql = "select count(1) as c1 from proc_parts_tech_amend t " +
//                " where t.change_mode=2 and  t.new_target_id=" + step.getRouteRevId();
//        int c1 = DbUtil.getJdbcTemplate().queryForObject(checkAmdRouteSql, Integer.class);
//        if(c1>0){
//            // 路线卡修改
//            // 不考虑新增后再删除的情况
//            needLogicDel = true;
//        }
        if(needLogicDel){
            // TODO 逻辑删除
            //  String delSql1 = "update spp_route_step set active=0 where route_step_id=";
            this.removeById(step.getRouteStepId());
        }else{
            this.removeById(step.getRouteStepId());
        }

        // 重排序该工序下的工步
        try{
            Long routeOpId = step.getRouteOpId();
            String opNo3 = step.getStepNum().substring(0,3);
            reorderRouteStep(routeOpId, opNo3);
        }catch(Exception ex){
            log.warn("删除工步后重排序出错:"+ex.getMessage());
        }
    }

    public void reorderRouteStep(Long routeOpId, String opNo3){

        // 重新排序路线卡的指定工序的有效工步
        String sql = "select route_step_id, step_no, step_num from spp_route_step where route_op_id=? and active=1";
        List<Map<String, Object>> stepList = DbUtil.getJdbcTemplate().queryForList(sql, routeOpId);
        if(CollectionUtils.isEmpty(stepList)){
            return;
        }
        // 按照工步号排序
        CollectionUtil.sort(stepList, new Comparator<Map<String, Object>>(){
            @Override
            public int compare(Map<String, Object> step1, Map<String, Object> step2) {
                String stepNo1 = MapUtil.getStr(step1, "step_no");
                if(ObjectUtils.isEmpty(stepNo1)){
                    return -1;
                }
                String stepNo2 = MapUtil.getStr(step2, "step_no");
                //防止同时存在2位和3位序号的情况
                return Integer.parseInt(stepNo1) - Integer.parseInt(stepNo2);
            }
        });
        // 检查排序后需要更新的记录
        List<Object[]> batchArgs = new ArrayList<Object[]>();
        for(int i=0; i<stepList.size(); i++){
            Map<String, Object> step = stepList.get(i);
            String stepNo = MapUtil.getStr(step, "step_no");
            String newStepNo = null;
            if(stepNo.length()==2) {
                newStepNo = String.format("%02d", i+1);
            }else if(stepNo.length()==3) {
                newStepNo = String.format("%03d", i+1);
            }
            if(!newStepNo.equals(stepNo)){
                // update step_no, step_num
                String stepNum = MapUtil.getStr(step, "step_num");
                if(ObjectUtils.isEmpty(stepNum)){
                    stepNum = opNo3 + String.format("%03d", i+1);
                }else{
                    stepNum = stepNum.substring(0, 3) + String.format("%03d", i+1);
                }
                batchArgs.add(new Object[]{newStepNo, stepNum, MapUtil.getLong(step,"route_step_id")});
            }
        }
        String updateSql = "update spp_route_step set step_no=?,step_num=? where route_step_id=?";
        if(CollectionUtils.isNotEmpty(batchArgs)){
            DbUtil.getJdbcTemplate().batchUpdate(updateSql, batchArgs);
        }
    }
}
